angular.module("app").controller("buyCtrl", ['$scope', '$state', '$stateParams', 'userInfo', '$rootScope', 'product', '$http', 'utils', '$filter', function(
	$scope,
	$state,
	$stateParams,
	userInfo,
	$rootScope,
	product,
	$http,
	utils,
	$filter
) {

	/*赋值预留手机号*/
	$scope.amount = userInfo.payamount //购买金额
	$scope.zhifu = Number($scope.amount) - Number(product.hongbao) //支付金额
	$scope.pwd = "" //交易密码
	$scope.code = "" //验证码
	$scope.type = userInfo.buy_type //获取支付方式
	$scope.productInfo = product.productInfo //获取产品信息
	$scope.discountList = [] //红包列表
	$scope.codeShow = false //验证码弹窗
	$scope.pwdShow = false //支付密码弹窗
	$scope.maskShow = false //遮罩层
	/*获取支付方式*/
	if($state.current.name == "buy") {

		$rootScope.isShow = false //关闭支付方式窗口
		$scope.type = $stateParams.type //获取支付方式
		userInfo.buy_type = $scope.type //存到服务里,订单详情要用
		$scope.Surplus = null //剩余可购
		userInfo.getUserBank().then(function(res) {
			$scope.userBankInfo = res.body.card
			userInfo.acc_id = res.body.card.acc_id
			userInfo.acc_number = res.body.card.acc_number
		})

		var arr = [] //临时可购金额排序数组
		if($scope.productInfo.cumulative_purchase_amount > 0) { //累计购买不等于0
			$http.post(utils.balanceSys, {}, {
				params: {
					header: utils.header("000034"),
					body: {
						user_code: userInfo.user_code,
						product_id: $scope.productInfo.product_id
					}
				}
			}).then(function(res) {
				if(res.header.re_code == "0000") {
					var leiji = $scope.productInfo.cumulative_purchase_amount - res.body.totalAmount //总的
					if($scope.productInfo.single_purchase_amount > 0) { //单笔购买不等于0
						arr.push(leiji)
						arr.push($scope.productInfo.pro_share) //剩余可购
						arr.push($scope.productInfo.single_purchase_amount) //单笔可购
						arr.sort(function(a, b) {
							return a - b
						})
						$scope.Surplus = arr[0]
					} else { //单笔等于0
						arr.push(leiji)
						arr.push($scope.productInfo.pro_share) //剩余可购
						arr.sort(function(a, b) {
							return a - b
						})
						$scope.Surplus = arr[0]
					}

				}
			})

		} else { //累计等于0
			if($scope.productInfo.single_purchase_amount == 0) {
				$scope.Surplus = $scope.productInfo.pro_share
			} else {
				arr.push($scope.productInfo.pro_share) //剩余可购
				arr.push($scope.productInfo.single_purchase_amount) //单笔可购
				arr.sort(function(a, b) {
					return a - b
				})
				$scope.Surplus = arr[0]
			}

		}

		/*产品名称*/
		$scope.couponInfo = false
		$scope.discountInfo = function() {
			
			/*如果是抵扣金*/
			if(product.Coupon.coupon_type == 1) {
				$scope.couponInfo = product.Coupon.coupon_value + "元抵扣金"
				return
			}
			/*如果是加息劵*/
			if(product.Coupon.coupon_type == 3) {
				/*如果同产品时长*/
				if(product.Coupon.is_eq_pro == 1) {
					$scope.couponInfo = "加息" + product.Coupon.coupon_rate + "%(" + $scope.productInfo.term + "天)"
					return
				} else {
					$scope.couponInfo = "加息" + product.Coupon.coupon_rate + "%(" + product.Coupon.increase_term + "天)"
					return
				}

			}

		}
		$scope.discountInfo()

		/*关闭验证码弹窗*/
		mui(document).on("tap", "#dialog_code", function() {
			$scope.maskShow = false;
			$scope.codeShow = false;
		})
		/*关闭支付密码弹窗*/
		mui(document).on("tap", "#dialog_pwd", function() {
			$scope.maskShow = false;
			$scope.pwdShow = false;
		})

		/*余额全投*/
		$scope.allThrow = function() {
			if(parseInt($scope.userBankInfo.acc_amount) > parseInt($scope.Surplus)) {
				$scope.amount = parseInt($scope.Surplus)
			} else {
				$scope.amount = parseInt($scope.userBankInfo.acc_amount)
			}
			this.jisuan()

		}

		/*选择红包*/
		$scope.checkDiscount = function() {
			userInfo.payamount = $scope.amount
			$state.go("discount")

		}

		/*动态计算收益*/
		$scope.jisuan = function() {
			xuanze()
			$scope.discountInfo()
			if(product.Coupon.coupon_type == 3) {
				var addlucre = 0
				if(product.Coupon.is_eq_pro == 1) {
					$scope.lucre = $scope.amount * $scope.productInfo.term * ($scope.productInfo.benchmark_return_rate + $scope.productInfo.increase_interest_return_rate) / 365
					addlucre = $scope.amount * $scope.productInfo.term * (product.Coupon.coupon_rate / 100) / 365
					$("#lucre").html($filter("jiequ")($scope.lucre) + "元+" + $filter("jiequ")(addlucre) + "元")
				} else {
					$scope.lucre = $scope.amount * $scope.productInfo.term * ($scope.productInfo.benchmark_return_rate + $scope.productInfo.increase_interest_return_rate) / 365
					addlucre = $scope.amount * product.Coupon.increase_term * (product.Coupon.coupon_rate / 100) / 365
					$("#lucre").html($filter("jiequ")($scope.lucre) + "元+" + $filter("jiequ")(addlucre) + "元")
				}

			} else {
				$scope.lucre = $scope.amount * $scope.productInfo.term * ($scope.productInfo.benchmark_return_rate + $scope.productInfo.increase_interest_return_rate) / 365
				$("#lucre").html($filter("jiequ")($scope.lucre))
			}

		}
		$scope.jisuan()

		/*选择最优红包*/
		$scope.discountList = []
		$http.get(utils.redSys, {
			params: {
				header: utils.header("180011"),
				body: {
					user_code: userInfo.user_code
				}
			}
		}).then(function(res) {
			if(res.header.re_code == "0000") {
				$scope.discountList = userInfo.sort($scope.amount, product.productInfo, res.body) //获取优惠券和抵扣金并排序
			}
		})

		function xuanze() {
			var money = 0
			if($scope.discountList.length > 0) {
				if(!$scope.amount) {
					money = 0
				} else {
					money = $scope.amount
				}
				$scope.discountList = userInfo.sort(money, product.productInfo, $scope.discountList)
				for(var i = 0; i < $scope.discountList.length; i++) {
					if($scope.discountList[i].available == 1) {
						if($scope.discountList[i].coupon_type == 1) {
							$scope.discountList[i].money = money * $scope.productInfo.term * ($scope.productInfo.benchmark_return_rate + $scope.productInfo.increase_interest_return_rate) / 365 + Number($scope.discountList[i].coupon_value)
						} else if($scope.discountList[i].coupon_type == 3) {
							if($scope.discountList[i].is_eq_pro == 1) {
								$scope.discountList[i].money = (money * $scope.productInfo.term * ($scope.productInfo.benchmark_return_rate + $scope.productInfo.increase_interest_return_rate) / 365) + (money * $scope.productInfo.term * ($scope.discountList[i].coupon_rate / 100) / 365)
							} else {
								$scope.discountList[i].money = (money * $scope.productInfo.term * ($scope.productInfo.benchmark_return_rate + $scope.productInfo.increase_interest_return_rate) / 365) + (money * $scope.discountList[i].increase_term * ($scope.discountList[i].coupon_rate / 100) / 365)
							}
						}
					} else {
						$scope.discountList[i].money = 0
					}

				}
				/*事件排序*/
				$scope.discountList.sort(function(a, b) {
					return new Date(a.expire_date) - new Date(b.expire_date)
				})
				/*按受益排序*/
				$scope.discountList.sort(function(a, b) {
					return b.money - a.money
				})

				if($scope.discountList[0].available == 1) {
					product.Coupon = $scope.discountList[0]
				} else {
					$scope.couponInfo = false
					product.Coupon = {}
				}

			}

		}

		/*购买下一步*/
		$scope.buyNext = function() {

			/*判断是否超过最大限额*/
			if($scope.amount > $scope.Surplus) {

				utils.msg("购买金额不能大于可购金额")
				return
			}

			/*低于单笔最低额度*/
			if(Number($scope.amount) < Number($scope.productInfo.purchase_amount)) {

				utils.msg("购买金额必须大于起购金额")
				return
			}

			if($scope.type == 1) { //如果是银行卡购买则判断
				if(Number($scope.amount) < Number($scope.userBankInfo.min_amount)) {
					utils.msg("低于单笔最低限额")
					return
				}

				if(Number($scope.amount) > Number($scope.userBankInfo.max_amount * 10000)) {
					utils.msg("超出银行卡支付限额，建议在官网充值后购买")
					return
				}
			}

			//超过等级配额
			$http.get(utils.productSys, {
				params: {
					header: utils.header("030510"),
					body: {
						amount: $scope.amount,
						user_code: userInfo.user_code,
						user_level: userInfo.risklevel
					}
				}
			}).then(function(res) {
				if(res.header.re_code == "0000") {

					var info = ""
					switch(userInfo.risklevel) {
						case 1:
							info = "保守型"
							break;
						case 2:
							info = "稳健型"
							break;
						case 3:
							info = "平稳型"
							break;
						case 4:
							info = "成长型"
							break;
						case 5:
							info = "进取型"
							break;
					}

					if(res.body.risk_validat == 1) { //限额
						mui.confirm('您的风险测评结果为<b>“' + info + '”</b>，本次购买后超过赚啦理财建议的资产总额' + res.body.asset_limit + '元', ' ', ['我知道了', '查看测评结果'], function(e) {
							if(e.index === 1) {
								$state.go("02_Evaluation")
								return
							}
						}, 'div')
						return
					}

					var hongbao = []
					var shichang = ""
					if($scope.couponInfo) {

						if(product.Coupon.is_eq_pro == 1) {
							shichang = $scope.productInfo.term
						} else {
							shichang = product.Coupon.increase_term
						}

						hongbao.push({
							"coupon_no": product.Coupon.coupon_no
						})
					}

					if($scope.type == 1) { //如果是银行卡购买

						$http.get(utils.OrderSys, {
								params: {
									header: utils.header("010010"),
									body: {
										acc_id: userInfo.acc_id,
										acc_number: userInfo.acc_number,
										amount: $scope.amount,
										order_source: "0",
										coupon_increase_term: shichang,
										order_type: "2",
										pro_id: $scope.productInfo.product_id,
										pro_type: $scope.productInfo.type,
										red_packet_list: hongbao,
										user_code: userInfo.user_code
									}
								}
							})

							.then(function(res) {
								if(res.header.re_code == "0000") {
									userInfo.order_id = res.body.order_id
									userInfo.order_type = res.body.order_type
									/*充值申请*/
									$http.get(utils.tradeSys, {
											params: {
												header: utils.header("000010"),
												body: {
													order_id: userInfo.order_id,
													user_code: userInfo.user_code
												}
											}
										})

										.then(function(res) {
											if(res.header.re_code == "0000") {
												/*判断跳转页面*/
												$http.get(utils.paySys, {
														params: {
															header: utils.header("020025"),
															body: {
																user_code: userInfo.user_code
															}
														}
													})

													.then(function(res) {
														if(res.header.re_code == "0000") {

															userInfo.pay_platform_type = res.body.status
															if(res.body.status == "0") {

																$http.get(utils.paySys, {
																	params: {
																		header: utils.header("020028"),
																		body: {
																			user_code: userInfo.user_code
																		}
																	}
																}).then(function(res) {
																	if(res.header.re_code == "0000") {
																		$scope.pre_phone = res.body.pre_phone
																	}
																})
																$scope.codeShow = true //验证码弹窗
																$scope.maskShow = true //遮罩层

															} else {
																$scope.pwdShow = true //支付密码弹窗
																$scope.maskShow = true //遮罩层
															}
														}

													})
											}

										})
								}
							})

					} else if($scope.type == 2) { //如果是钱包购买

						$http.get(utils.OrderSys, {
							params: {
								header: utils.header("010010"),
								body: {
									acc_id: userInfo.acc_id,
									acc_number: userInfo.acc_number,
									amount: $scope.amount,
									order_source: "0",
									coupon_increase_term: shichang,
									order_type: "3",
									pro_id: $scope.productInfo.product_id,
									pro_type: $scope.productInfo.type,
									red_packet_list: hongbao,
									user_code: userInfo.user_code
								}
							}
						}).then(function(res) {
							if(res.header.re_code == "0000") {
								userInfo.order_id = res.body.order_id
								userInfo.payamount = $scope.amount
								userInfo.pay_platform_type = 1
								userInfo.order_type = res.body.order_type
								$scope.pwdShow = true //支付密码弹窗
								$scope.maskShow = true //遮罩层
							}
						})

					}

				}
			})

		}
	}

	/* 优惠券*/
	if($state.current.name == "discount") {

		/*获取加息劵和抵扣金*/
		$http.get(utils.redSys, {
			params: {
				header: utils.header("180011"),
				body: {
					user_code: userInfo.user_code
				}
			}
		}).then(function(res) {
			if(res.header.re_code == "0000") {
				$scope.discountList = userInfo.sort($scope.amount, product.productInfo, res.body) //获取优惠券和抵扣金并排序
			}
		})

		/*初始化slider*/
		var Slider = mui('#productTab').slider()
		$scope.$on('$viewContentLoaded', function(event) {
			setTimeout(function() {
				/*设置滚动区域高度*/
				$('.mui-content').css('height', $(window).height() - 44 + 'px')
				$('.mui-slider-group').css('height', $(window).height() - $('.mui-slider-group').offset().top + 'px');
				$('.mui-scroll').css('min-height', $(window).height() - $('.mui-slider-group').offset().top + 'px')

				mui('.mui-scroll-wrapper').scroll({
					scrollY: true, //是否竖向滚动
					scrollX: false, //是否横向滚动
					startX: 0, //初始化时滚动至x
					startY: 0, //初始化时滚动至y
					indicators: true, //是否显示滚动条
					deceleration: 0.0006, //阻尼系数,系数越小滑动越灵敏
					bounce: true //是否启用回弹
				});
			}, 200)

		})

		/*手动触发滑动*/
		$(".product_Tab_Title").find("span").on("click", function() {
			Slider.gotoItem($(this).index())
			$(".product_Tab_Title").find("span").eq($(this).index()).addClass("mui-active").siblings().removeClass("mui-active")
		})
		/*监听事件*/
		$('#productTab').on("slide", function(e) {
			$(".product_Tab_Title").find("span").eq(e.detail.slideNumber).addClass("mui-active").siblings().removeClass("mui-active")
		})

		$scope.coupon_no = {}

		/*监听checked事件*/

		$(document).on("click", "input[type=radio]", function() {

			product.Coupon = $scope.coupon_no
			
			$(document).off('click', 'input[type=radio]')
			history.go(-1)

		})

	}

	/*订单确认*/
	if($state.current.name == "confirmOrder") {
		$scope.redlist = product.redlist //红包列表
		$scope.rednum = product.rednum
		product.hongbao = 0 //红包清0
		$scope.redlist.sort(function(a, b) {
			return b.coupon_value - a.coupon_value;
		})

		for(var i = 0; i < $scope.redlist.length - 1; i++) {
			for(var j = 0; j < $scope.redlist.length - 1 - i; j++) {
				var cur = $scope.redlist[j];
				if(cur.coupon_value == $scope.redlist[j + 1].coupon_value) { //如果金额相同
					if(new Date(cur.expire_date) > new Date($scope.redlist[j + 1].expire_date)) { //按到期时间排序
						var temp = cur
						cur = $scope.redlist[j + 1]
						$scope.redlist[j + 1] = temp
					} else {
						if(cur.least_amount > $scope.redlist[j + 1].least_amount) { //按最小可用金额排序
							var temp = cur
							cur = $scope.redlist[j + 1]
							$scope.redlist[j + 1] = temp
						}

					}

				}

			}

		}

		product.redlist = angular.copy($scope.redlist)
		for(var i = 0; i < $scope.redlist.length; i++) {
			if($scope.amount < $scope.redlist[i].coupon_value || $scope.amount < $scope.redlist[i].least_amount) { //如果购买金额小于红包额度
				$scope.redlist.splice(i, 1);
				i--
				continue
			}

			if($scope.redlist[i].upper_term != 0 || $scope.redlist[i].floor_term != 0) {
				if(product.productInfo.term < $scope.redlist[i].floor_term) { //红包期限不匹配
					$scope.redlist.splice(i, 1);
					i--
					continue
				}
				if(product.productInfo.term > $scope.redlist[i].upper_term && $scope.redlist[i].upper_term != 0) {
					$scope.redlist.splice(i, 1);
					i--
					continue
				}

			} else {
				if($scope.redlist[i].floor_term != 0) { //如果最大期限等于0,最小期限不等于0
					if(product.productInfo.term < $scope.redlist[i].floor_term) {
						$scope.redlist.splice(i, 1);
						i--
						continue
					}

				}

			}
		}

		$scope.order_tijiao = function() {
			$scope.hongbao = []

			if($scope.redlist.length != 0) {
				$scope.hongbao.push({
					"coupon_no": $scope.redlist[0].coupon_no
				})
			}

			if($scope.hongbao.length != 0) {

				product.hongbao = $scope.redlist[0].coupon_value
			}

			if($scope.type == 1) { //如果是银行卡购买

				$http.get(utils.OrderSys, {
						params: {
							header: utils.header("010010"),
							body: {
								acc_id: userInfo.acc_id,
								acc_number: userInfo.acc_number,
								amount: $scope.amount,
								order_source: "0",
								order_type: "2",
								pro_id: $scope.productInfo.product_id,
								pro_type: $scope.productInfo.type,
								red_packet_list: $scope.hongbao,
								user_code: userInfo.user_code
							}
						}
					})

					.then(function(res) {
						if(res.header.re_code == "0000") {
							userInfo.order_id = res.body.order_id
							userInfo.order_type = res.body.order_type
							/*充值申请*/
							$http.get(utils.tradeSys, {
									params: {
										header: utils.header("000010"),
										body: {
											order_id: userInfo.order_id,
											user_code: userInfo.user_code
										}
									}
								})

								.then(function(res) {
									if(res.header.re_code == "0000") {
										/*判断跳转页面*/
										$http.get(utils.paySys, {
												params: {
													header: utils.header("020025"),
													body: {
														user_code: userInfo.user_code
													}
												}
											})

											.then(function(res) {
												if(res.header.re_code == "0000") {
													userInfo.payamount = $scope.amount
													userInfo.pay_platform_type = res.body.status
													if(res.body.status == "0") {
														$state.go("confirmBuyCode") //验证码界面
													} else {
														$state.go("confirmBuy") //支付密码界面
													}
												}

											})
									}

								})
						}

					})

			} else if($scope.type == 2) { //如果是钱包购买

				$http.get(utils.OrderSys, {
					params: {
						header: utils.header("010010"),
						body: {
							acc_id: userInfo.acc_id,
							acc_number: userInfo.acc_number,
							amount: $scope.amount,
							order_source: "0",
							order_type: "3",
							pro_id: $scope.productInfo.product_id,
							pro_type: $scope.productInfo.type,
							red_packet_list: $scope.hongbao,
							user_code: userInfo.user_code
						}
					}
				}).then(function(res) {
					if(res.header.re_code == "0000") {
						userInfo.order_id = res.body.order_id
						userInfo.payamount = $scope.amount
						userInfo.pay_platform_type = 1
						userInfo.order_type = res.body.order_type
						$state.go("confirmBuy") //支付密码界面

					}

				})

			}

		}

	}

	/*优惠券*/
	if($state.current.name == "Coupon") {
		$scope.canuse = true //是否有可用红包
		$scope.isall = false //是否全都没选择
		$scope.zong = [] //选中数组
		$http.get(utils.redSys, {
			params: {
				header: utils.header("180011"),
				body: {
					user_code: userInfo.user_code
				}
			}
		}).then(function(res) {
			if(res.header.re_code == "0000") {
				$scope.redlist = res.body
				$scope.redlist.sort(function(a, b) {
					return b.coupon_value - a.coupon_value;
				})

				for(var i = 0; i < $scope.redlist.length - 1; i++) {
					for(var j = 0; j < $scope.redlist.length - 1 - i; j++) {
						var cur = $scope.redlist[j];
						if(cur.coupon_value == $scope.redlist[j + 1].coupon_value) { //如果金额相同
							if(new Date(cur.expire_date) > new Date($scope.redlist[j + 1].expire_date)) { //按到期时间排序
								var temp = cur
								cur = $scope.redlist[j + 1]
								$scope.redlist[j + 1] = temp
							} else {
								if(cur.least_amount > $scope.redlist[j + 1].least_amount) { //按最小可用金额排序
									var temp = cur
									cur = $scope.redlist[j + 1]
									$scope.redlist[j + 1] = temp
								}

							}

						}

					}

				}

				for(var i = 0; i < $scope.redlist.length; i++) {
					if($scope.amount < $scope.redlist[i].coupon_value || $scope.amount < $scope.redlist[i].least_amount) { //如果购买金额小于红包额度
						$scope.redlist.splice(i, 1);
						i--
						continue
					}

					if($scope.redlist[i].upper_term != 0 || $scope.redlist[i].floor_term != 0) {
						if(product.productInfo.term < $scope.redlist[i].floor_term) { //红包期限不匹配
							$scope.redlist.splice(i, 1);
							i--
							continue
						}
						if(product.productInfo.term > $scope.redlist[i].upper_term && $scope.redlist[i].upper_term != 0) {
							$scope.redlist.splice(i, 1);
							i--
							continue
						}

					} else {
						if($scope.redlist[i].floor_term != 0) { //如果最大期限等于0,最小期限不等于0
							if(product.productInfo.term < $scope.redlist[i].floor_term) {
								$scope.redlist.splice(i, 1);
								i--
								continue
							}

						}

					}
				}
				//设置选择状态
				if($scope.redlist.length == 0) {
					$scope.redlist = product.redlist
					$scope.canuse = false //没有可用红包
				} else {
					product.rednum = true //设置有可用红包
					angular.forEach($scope.redlist, function(value, index) {
						if(index == 0) {
							value.selected = true
							$scope.zong = []
							$scope.zong.push(value)
						} else {
							value.selected = false
						}
					})
				}
				//勾选操作数组
				$scope.selected = function(item) {
					angular.forEach($scope.redlist, function(value, index) {
						if(index != item) {
							value.selected = false
							$(".coupon [type=checkbox]").eq(index).prop("checked", false)
						}

					})

					$scope.zong = $.map($(".coupon [type=checkbox]:checked"), function(v, k) {
						if(angular.isDefined($(v).attr("info"))) {
							return JSON.parse($(v).attr("info"))
						}
					});

				}

				$scope.$watch('zong', function(news, olds) {
					if(news.length == 0 && $scope.canuse == true) {
						$scope.isall = true
					} else {
						$scope.isall = false
					}
				}, true)

				$scope.save = function() {
					product.redlist = $scope.zong
					history.go(-1)

				}

			}

		})

	}

	//购买确认
	$scope.paytwo = function() {
		$http.get(utils.tradeSys, {
			params: {
				header: utils.header("000012"),
				body: {
					order_id: userInfo.order_id, //订单id
					order_type: userInfo.order_type, //购买类型
					pay_platform_type: userInfo.pay_platform_type, //支付平台类型
					tra_password: md5($scope.pwd),
					user_code: userInfo.user_code,
					vercd: $scope.code //验证码
				}
			}
		}).then(function(res) {
			if(res.header.re_code == "0000") {
				$state.go("buyInfo")
			}
		})
	}

	/*订单详情*/
	if($state.current.name == "buyInfo") {
		product.hongbao = 0 //清空红包金额
		$http.get(utils.OrderSys, {
			params: {
				header: utils.header("010060"),
				body: {
					order_id: userInfo.order_id
				}
			}
		}).then(function(res) {

			if(res.header.re_code == "0000") {
				$scope.orderInfo = res.body
				$scope.buy_type = userInfo.buy_type
			}

		})

	}

}])